﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinBookKeeping.Models;
using WinBookKeeping.Utility;

namespace WinBookKeeping
{
    public partial class FrmDayStatisitics : Form
    {
        private const decimal ABNORMAL_THRESHOLD = 1.5M; // 异常消费阈值（平均值的1.5倍）
        private const decimal SAVING_THRESHOLD = 0.8M;   // 节约阈值（平均值的0.8倍）
        private const int TREND_DAYS = 7;                // 趋势分析天数

        public FrmDayStatisitics()
        {
            InitializeComponent();
        }
        //收入、支出、收支、最高/最低日支出
        decimal todayIn = 0.00M,
                todayEx = 0.00M,
                todayInEx = 0.00M,
                highestEx = 0.00M,
                lowestEx = 0.00M;
        //收支记录列表
        List<RecordInfo> recordList = new List<RecordInfo>();
        //日统计数据列表
        List<DayStatInfo> dayStatList = new List<DayStatInfo>();

        private async void FrmDayStatisitics_Load(object sender, EventArgs e)
        {
            //按日统计数据
            await StatisticsData();
            //分析消费行为
            AnalyzeConsumptionBehavior();
        }

        private void btnStatistic_Click(object sender, EventArgs e)
        {
            StatisticsData();
            AnalyzeConsumptionBehavior();
        }
        private async Task StatisticsData()
        {
            lvInExDataList.Items.Clear();
            //加载所有收支记录
            await LoadAllRecordList();
            //按日统计收支数据并加载列表
            StatisticsDayList();
            //加载今日收支数据
            LoadStatInfo();
        }

        private async Task LoadAllRecordList()
        {
            //重置
            todayIn = 0.00M;
            todayEx = 0.00M;
            todayInEx = 0.00M;
            highestEx = 0.00M;
            lowestEx = 0.00M;
            recordList = await CommonHelper.GetAllRecordList();
        }

        //按日统计数据并加载
        private void StatisticsDayList()
        {
            dayStatList.Clear();
            //筛选日期列表
            List<string> listDate = recordList.Select(r => r.RecordTime.ToString("yyyy-MM-dd")).Distinct().ToList();
            //按日期列表统计处理--今日收支、最高/最低支出
            foreach(string date in listDate)
            {
                var list = recordList.Where(r => r.RecordTime.ToString("yyyy-MM-dd") == date);
                decimal inTotal = 0.00M, exTotal = 0.00M, inexTotal = 0.00M;
                //遍历筛选的记录列表
                foreach(var record in list)
                {
                    if(record.ItemType=="收入")
                    {
                        inTotal += record.Money;
                    }
                    else
                    {
                        exTotal += record.Money;
                    }
                }
                inexTotal = inTotal - exTotal;//当日收支
                //如果当前date为今日日期则保存今日数据
                if(date==DateTime.Today.ToString("yyyy-MM-dd"))
                {
                    todayIn = inTotal;
                    todayEx = exTotal;
                    todayInEx = inexTotal;
                }
                //当前的收支情况添加到统计列表
                dayStatList.Add(new DayStatInfo()
                {
                    Date=date,
                    InExTotal=inexTotal,
                    InTotal=inTotal,
                    ExTotal=exTotal
                });
            }
            
            //加载统计列表
            if(dayStatList.Count>0)
            {
                var exList = dayStatList.Select(d => d.ExTotal);
                highestEx = exList.Max();//最高日支出
                lowestEx = exList.Min();//最低日支出
                foreach(DayStatInfo item in dayStatList)
                {
                    ListViewItem li = new ListViewItem();
                    li.Text = item.Date;
                    li.SubItems.Add("￥" + item.InTotal.ToString("0.00"));
                    li.SubItems.Add("￥" + item.ExTotal.ToString("0.00"));
                    li.SubItems.Add("￥" + item.InExTotal.ToString("0.00"));
                    lvInExDataList.Items.Add(li);
                }
            }
        }

        //加载统计数据
        private void LoadStatInfo()
        {
            lblTodayIn.Text = "￥" + todayIn.ToString("0.00") + " 元";
            lblTodayEx.Text = "￥" + todayEx.ToString("0.00") + " 元";
            lblTodayInEx.Text = "￥" + todayInEx.ToString("0.00") + " 元";
            lblHighestEx.Text = "￥" + highestEx.ToString("0.00") + " 元";
            lblLowestEx.Text = "￥" + lowestEx.ToString("0.00") + " 元";
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void ListInEx_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void label3_Click(object sender, EventArgs e)
        {
            
        }

        //分析消费行为
        private void AnalyzeConsumptionBehavior()
        {
            if (dayStatList.Count == 0) return;

            var analysis = new StringBuilder();
            
            // 1. 计算平均日支出
            decimal avgDailyExpense = dayStatList.Average(d => d.ExTotal);
            
            // 2. 分析今日支出
            if (todayEx > avgDailyExpense * ABNORMAL_THRESHOLD)
            {
                analysis.AppendLine($"⚠️ 今日支出（￥{todayEx:0.00}）显著高于日均支出（￥{avgDailyExpense:0.00}），建议控制支出。");
            }
            else if (todayEx < avgDailyExpense * SAVING_THRESHOLD)
            {
                analysis.AppendLine($"✅ 今日支出（￥{todayEx:0.00}）低于日均支出（￥{avgDailyExpense:0.00}），继续保持！");
            }

            // 3. 分析消费趋势
            var recentDays = dayStatList.OrderByDescending(d => d.Date).Take(TREND_DAYS).ToList();
            if (recentDays.Count >= 3)
            {
                var trend = AnalyzeTrend(recentDays);
                analysis.AppendLine(trend);
            }

            // 4. 分析异常消费
            var abnormalDays = dayStatList.Where(d => d.ExTotal > avgDailyExpense * ABNORMAL_THRESHOLD).ToList();
            if (abnormalDays.Any())
            {
                analysis.AppendLine("\n📊 异常消费提醒：");
                foreach (var day in abnormalDays)
                {
                    analysis.AppendLine($"• {day.Date} 支出 ￥{day.ExTotal:0.00}，超出日均支出 {((day.ExTotal / avgDailyExpense - 1) * 100):0.0}%");
                }
            }

            // 5. 生成节约建议
            analysis.AppendLine("\n💡 节约建议：");
            if (todayEx > avgDailyExpense)
            {
                analysis.AppendLine($"• 今日支出较高，建议减少非必要支出");
            }
            if (dayStatList.Count >= 7)
            {
                var weeklyAvg = dayStatList.TakeLast(7).Average(d => d.ExTotal);
                if (weeklyAvg > avgDailyExpense)
                {
                    analysis.AppendLine($"• 本周平均日支出（￥{weeklyAvg:0.00}）高于历史平均，建议控制日常开销");
                }
            }

            // 6. 收入支出比分析
            if (todayIn > 0)
            {
                decimal incomeExpenseRatio = todayEx / todayIn;
                if (incomeExpenseRatio > 0.8M)
                {
                    analysis.AppendLine($"• 今日支出占收入比例较高（{incomeExpenseRatio:P0}），建议适当控制支出");
                }
            }

            // 显示分析结果
            txtAnalysis.Text = analysis.ToString();
        }

        private string AnalyzeTrend(List<DayStatInfo> recentDays)
        {
            var trend = new StringBuilder();
            trend.AppendLine("\n📈 消费趋势分析：");

            // 计算趋势
            var expenses = recentDays.Select(d => d.ExTotal).ToList();
            bool isIncreasing = true;
            bool isDecreasing = true;

            for (int i = 1; i < expenses.Count; i++)
            {
                if (expenses[i] <= expenses[i - 1]) isIncreasing = false;
                if (expenses[i] >= expenses[i - 1]) isDecreasing = false;
            }

            if (isIncreasing)
            {
                trend.AppendLine("• 近期支出呈上升趋势，请注意控制支出");
            }
            else if (isDecreasing)
            {
                trend.AppendLine("• 近期支出呈下降趋势，继续保持！");
            }
            else
            {
                trend.AppendLine("• 近期支出波动较大，建议保持稳定消费习惯");
            }

            // 计算波动率
            decimal maxExpense = expenses.Max();
            decimal minExpense = expenses.Min();
            decimal volatility = (maxExpense - minExpense) / minExpense;
            
            if (volatility > 0.5M)
            {
                trend.AppendLine($"• 支出波动较大（波动率 {volatility:P0}），建议保持稳定消费习惯");
            }

            return trend.ToString();
        }
    }
}
